package com.hxd;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.hxd.base.BaseEntity;
import com.hxd.common.utils.StringUtils;

public class MybatisGenerator {

	public static final String db_url = "jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT";
	public static final String db_user_name = "root";
	public static final String db_user_password = "root";
	public static final String package_path = "com.hxd";
	public static final String file_path_base = "/src/main/java/com/hxd/";
	
	/**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        @SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器	
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("zhoujw");
        gc.setOpen(false);
        gc.setServiceName("%sService");
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(db_url);
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(db_user_name);
        dsc.setPassword(db_user_password);
        mpg.setDataSource(dsc);

        //模块名
        String moduleIn = "";
        String moduleName = StringUtils.isEmpty(moduleIn) ? "" : moduleIn + "/";
        
        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent(package_path);
        if(StringUtils.isNotEmpty(moduleIn)) {
        	pc.setMapper("mapper." + moduleIn);
        	pc.setService("service." + moduleIn);
        	pc.setServiceImpl("service." + moduleIn + ".impl");
        	pc.setController("controller." + moduleIn);
        }
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + moduleName
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        
        // 自定义vo配置
        focList.add(new FileOutConfig("/templates/vo.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + file_path_base +"pojo/" + moduleName;
                return String.format((expand  + "%s" + ".java"), tableInfo.getEntityName() + "VO");
            }
        });
        
        // 自定义controller配置
        focList.add(new FileOutConfig("/templates/controller.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + file_path_base +"controller/" + moduleName;
                return String.format((expand  + "%s" + ".java"), tableInfo.getControllerName());
            }
        });
        
        // 自定义service配置
        focList.add(new FileOutConfig("/templates/service.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String expand = projectPath + file_path_base + "service/" + moduleName;
                return String.format((expand  + "%s" + ".java"), tableInfo.getServiceName());
            }
        });
        
		// 自定义serviceimp配置
		focList.add(new FileOutConfig("/templates/serviceimpl.java.ftl") {
		    @Override
		    public String outputFile(TableInfo tableInfo) {
		        String expand = projectPath + file_path_base + "service/" + moduleName + "impl/";
		        return String.format((expand  + "%s" + ".java"), tableInfo.getServiceImplName());
		    }
		});
        
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(BaseEntity.class);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("com.hxd.base.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns(new String[]{"id","create_id","create_time","update_time","delete_flag"});
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
    
}
